package shweixin

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/comment"
	"yundian/internel/app/models/goods"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/room"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/wxpay"
)

// 查看工单列表
func HandleServiceOrderList(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	//userId := 1

	param := &request.NotificationListReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.MemberId = userId
	data := dao.NewNotificationDaoDao().GetUserNotificationServiceList(param)
	NotificationList := data.Unwrap().([]*request.NotificationListRes)

	var notificationIds []int
	for _, item := range NotificationList {
		notificationIds = append(notificationIds, item.Id)
	}
	if len(notificationIds) > 0 {
		goodsList := dao.NewGoodsDao().GetGoodsListByNotificationIds(notificationIds).Unwrap().([]*request.NotificationListRes)
		for _, item := range NotificationList {
			for _, goodsItem := range goodsList {
				if item.Id == goodsItem.Id {
					item.GoodsId = goodsItem.GoodsId
					item.GoodsName = goodsItem.GoodsName
					item.CommentId = goodsItem.CommentId
					break
				}
			}
		}
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 查看工单详情
func HandleServiceOrderDetails(c *gin.Context) {
	userId, _ := helper.GetUserIdFromCtx(c)
	param := &request.NotificationListReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.MemberId = userId

	notificationDetails := dao.NewNotificationDaoDao().GetUserNotificationServiceInfo(param).Unwrap().(*request.NotificationDetailsRes)
	Response(c)("", CodeSuccess, notificationDetails)(OK)
	return
}

// 查看工单详情
func HandleServiceRoomOrderDetails(c *gin.Context) {
	userId, _ := helper.GetUserIdFromCtx(c)
	param := &request.NotificationListReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.MemberId = userId

	notificationDetails := dao.NewNotificationDaoDao().GetUserNotificationServiceRoomInfo(param).Unwrap().(*request.NotificationRoomDetailsRes)
	orderList := dao.NewRoomDaoDao().GetAdminRoomOrdersByNotificationIds([]int{notificationDetails.Id}).Unwrap().([]*room.Order)
	if len(orderList) > 0 {
		notificationDetails.DayLen = orderList[0].DayLen
		notificationDetails.Amount = orderList[0].Amount
		notificationDetails.TradeNo = orderList[0].TradeNo
		notificationDetails.RoomOrderStatus = orderList[0].Status
	}

	Response(c)("", CodeSuccess, notificationDetails)(OK)
	return
}

//工单列表修改
func HandleServiceOrderUpdate(c *gin.Context) {
	param := &placemodel.PlacesServiceNotification{}
	dingo.ErrorIf(c.Bind(param))

	Response(c)("", CodeSuccess, dao.NewNotificationDaoDao().UpdateUserNotificationServiceInfo(param).Unwrap())(OK)
}

//好评有礼工单详情
func HandleCommentDetails(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.CommentInfoReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//param.MemberId = 1
	param.MemberId = userId

	commentInfoDetails := dao.NewNotificationDaoDao().GetCommentDetails(param).Unwrap().(*request.CommentDetailsInfoRes)
	commentInfoDetails.PlaceAddress = commentInfoDetails.Province + commentInfoDetails.City + commentInfoDetails.County + commentInfoDetails.PlaceAddress

	if commentInfoDetails.GoodsType == helper.TypeNumGoodsTypeCash {
		redPacket := dao.NewNotificationDaoDao().GetCommentRedPacketReceiveListByOrderIds([]int{commentInfoDetails.GoodsOrderId})
		redPacketList := redPacket.Unwrap().([]*comment.SendRedPacketRecord)
		if len(redPacketList) > 0 {
			commentInfoDetails.GrantStatus = redPacketList[0].Status
		}
	}

	Response(c)("", CodeSuccess, commentInfoDetails)(OK)
	return
}

// 好评红包领取通知
func HandleCommentRedPacketReceiveInform(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	params := &comment.SendRedPacketRecord{}
	dingo.ErrorIf(c.ShouldBindJSON(params)).Unwrap()
	params.MemberId = userId
	params.Status = helper.TypeNumRedPacketStatusAlready

	if dao.NewNotificationDaoDao().UpdateRedPacketReceiveInfo(params).Err != nil {
		Response(c)("", CodeInternalServerError, nil)(OK)
		return
	}

	Response(c)("", CodeSuccess, true)(OK)
}

// 好评红包领取
func HandleCommentRedPacketReceive(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.ThirdCommentSubmitReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.MemberId = userId

	receiveData := dao.NewNotificationDaoDao().GetCommentRedPacketReceiveInfo(param).Unwrap().(*comment.SendRedPacketRecord)
	if receiveData.Id == 0 {
		Response(c)("", CodeInvalidParam, nil)(OK)
		return
	}
	if receiveData.ReceiveInfo != "" {
		Response(c)("", CodeSuccess, receiveData.ReceiveInfo)(OK)
		return
	}

	resultData := wxpay.NewPayData()
	if resultData, err = logic.NewWxApiCommon().HandleSendRedPacket(receiveData.XcxOpenid, receiveData.MchSendId, receiveData.Money); err != nil {
		Response(c)("", CodeInternalServerError, nil)(OK)
		return
	}

	resultData.Set("id", receiveData.Id)
	updateData := &comment.SendRedPacketRecord{}
	updateData.Id = receiveData.Id
	updateData.ReceiveInfo = resultData.ToJson()
	if dao.NewNotificationDaoDao().UpdateRedPacketReceiveInfo(updateData).Err != nil {
		Response(c)("", CodeInternalServerError, nil)(OK)
		return
	}

	Response(c)("", CodeSuccess, resultData.ToJson())(OK)
	return
}

// 好评提交
func HandleCommentSubmit(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.ThirdCommentSubmitReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//param.MemberId = 1
	param.MemberId = userId

	// 提交限制 24小时内3次
	if dao.NewNotificationDaoDao().GetCommentSubmitNum(param.MemberId, 24).Unwrap().(int64) >= 3 {
		Response(c)("提交过于频繁", CodeError, nil)(OK)
		return
	}

	imgByte, _ := json.Marshal(param.ImgStrArray)
	param.ImgList = string(imgByte)

	//生成通知记录
	m := &placemodel.PlacesServiceNotification{}
	m.MemberId = param.MemberId
	m.PlaceId = param.PlaceId
	m.MemberPhone = param.Phone
	m.PlaceName = param.PlaceName
	m.PlaceRoom = param.PlaceRoom
	m.DeviceSn = param.DeviceSn
	m.NotificationType = 9
	m.Status = 4
	m.Info = "好评有礼"
	notificationInfo := logic.NewShWxNotificationsLogic().InitNotificationsData(m)
	param.NotificationId = notificationInfo.Id

	//生成商品订单
	param.TradeNo = logic.NewOrderLogic().TradeNo
	ordersInfo := dao.NewGoodsDao().CreateGoodsOrder(param).Unwrap().(*goods.OrderUpdate)
	param.GoodsOrderId = ordersInfo.Id

	param.NotificationId = notificationInfo.Id
	param.Status = 1
	commentInfo := dao.NewNotificationDaoDao().CommentSubmit(param).Unwrap().(*request.ThirdCommentSubmitReq)
	Response(c)("", CodeInsertSuccess, map[string]interface{}{
		"commentId":      commentInfo.Id,
		"notificationId": notificationInfo.Id,
	})(OK)
	return
}

// HandleSetCommentGoods 确定盲盒抽奖商品
func HandleSetCommentGoods(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	param := &request.ThirdCommentSubmitReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.MemberId = userId

	commentData := dao.NewNotificationDaoDao().SetCommentGoods(param)
	Response(c)("", CodeInsertSuccess, commentData.Err != nil)(OK)
}

//查询地址
func HandleGetUserAddress(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	//userId := 1
	address := dao.NewNotificationDaoDao().GetUserAddress(userId).Unwrap().([]*membermodel.MemberAddress)
	Response(c)("", CodeSuccess, address)(OK)
	return
}

//查询地址详情
func HandleGetUserAddressDetails(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &membermodel.MemberAddress{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//param.MemberId = 1
	param.MemberId = userId

	addressInfoDetails := dao.NewNotificationDaoDao().GetUserAddressDetails(param).Unwrap().(membermodel.MemberAddress)

	Response(c)("", CodeSuccess, addressInfoDetails)(OK)
	return
}

func HandleRemoveUserAddress(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &membermodel.MemberAddress{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.MemberId = userId

	if data := dao.NewNotificationDaoDao().RemoveUserAddress(param); data.Err != nil {
		Response(c)("", CodeInternalServerError, false)(OK)
		return
	}

	Response(c)("", CodeDeleteSuccess, true)(OK)
}

func HandleUpdateUserAddress(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &membermodel.MemberAddress{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//param.MemberId = 1
	param.MemberId = userId

	addressInfoDetails := dao.NewNotificationDaoDao().UpdateUserAddress(param).Unwrap().(*membermodel.MemberAddress)

	Response(c)("", CodeSuccess, addressInfoDetails)(OK)
	return
}

//保存地址
func HandleCreateUserAddress(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &membermodel.MemberAddress{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	//param.MemberId = 1
	param.MemberId = userId
	param.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	param.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	addressInfo := dao.NewNotificationDaoDao().CreateUserAddress(param).Unwrap().(*membermodel.MemberAddress)
	Response(c)("", CodeInsertSuccess, addressInfo.Id)(OK)
}

//加盟信息提交
func HandleLeagueSubmit(c *gin.Context) {

	param := &users.CooperationRegister{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.CreateAt = time.Now().Format("2006-01-02 15:04:05")

	leagueInfo := dao.NewUserDao().LeagueInfoCreate(param).Unwrap().(*users.CooperationRegister)
	Response(c)("", CodeInsertSuccess, leagueInfo.ID)(OK)
}

//查询公告
func HandleGetPlaceBulletin(c *gin.Context) {
	param := &struct {
		PlaceId int `json:"placeId"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	m := dao.NewPlaceDao().GetPlaceBulletinById(param.PlaceId).Unwrap().(*placemodel.PlaceModel)
	Response(c)("", CodeInsertSuccess, m.Bulletin)(OK)
}
